<!--log list -->
<template>
  <div shadow="never"
       class="aui-card--fill log_lisinfo">
    <div class="query_condtions">
      <div class="condition_lf"
           style="font-size:16px;color:#404040;font-weight:600">
        API List
      </div>
      <div class="condition_rg">
        <el-select v-model="dataForm.status"
                   style="width:144px;margin-left:15px"
                   @change="getDataList"
                   clearable>
          <el-option label="All"
                     value=""></el-option>
          <el-option label="Succeeded"
                     value="200 OK"></el-option>
          <el-option label="Failed"
                     value="500"></el-option>
        </el-select>
      </div>
    </div>
    <el-table v-loading="loading"
              :data="dataList"
              @row-click="showDetail"
              header-cell-class-name="log_list_headers"
              :height="tableHeight"
              style="width: 100%;border:1px solid #EBEEF5;border-bottom:0">
              <!--               :row-class-name="tableRowClassName" -->
      <el-table-column prop='action'
                       :label="$t('custom.connector.loginfo.api')"
                       header-align="center"
                       align="center"
                       width="150"></el-table-column>
      <el-table-column prop="lastSyncDate"
                       :label="$t('custom.connector.loginfo.lastSycnTime')"
                       header-align="center"
                       align="center">
          <template slot-scope="scope">{{ timeAreaFormat(scope.row.lastSyncDate?scope.row.lastSyncDate:0)}}</template>
      </el-table-column>
      <el-table-column prop="status"
                       :label="$t('custom.connector.loginfo.status')"
                       header-align="center"
                       align="center">
        <template slot-scope="scope">
          <div style="width:84px;height:24px;line-height:20px;margin:0 auto;"
               :class="statusStyle(scope.row)">{{getStatus(scope.row)}}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('custom.connector.loginfo.action')"
                       header-align="center"
                       align="center">
        <template slot-scope="scope">
          <el-tooltip :open-delay="1000" content="Sync Data"
                      placement="top">
            <el-button v-loading="scope.row.btnLoading"
                       type="text"
                       v-if="scope.row.apiService&&scope.row.client"
                       @click.native.stop="manuallySync(scope.row,scope.$index)"><i class="cuifont icon_arrow_generate"></i>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-drawer style="position:fixed;width:724px;height:100%;top:0;right:0;z-index:2013;"
               :visible.sync="detailVisible"
               :direction="'rtl'"
               @opened="openedHander"
               @closed="closedHander"
               :show-close="false"
               :append-to-body="true"
               :custom-class="'connentor_drawer'"
               type="primary">
      <div slot="title"
           style="display:flex;justify-content:space-between">
        <div style="display:flex;justify-content:flex-start;font-weight:600;color:#404040">
          <span class="cusers cuifont icon_arrow_left"
                @click="detailVisible = false"
                style="margin-right:20px"></span>
          <span>{{datailInfo.action}}</span>
        </div>
        <div style="color:#404040;font-weight:400">
          <el-tooltip :open-delay="1000" content="Refresh"
                      placement="top">
            <span style="font-size:14px;padding:7px;magin-left:10px"
                  class="cuser cuifont icon_arrow_sync"
                  @click="refreshData">
            </span>
          </el-tooltip>
          <view-linked-info :linkKey="`${itemInfo.sync.subjectCode}wiki`"></view-linked-info>
          <span style="font-size:14px;padding:7px;margin-left:10px"
                class="cuser cuifont icon_dismiss"
                @click="detailVisible=!detailVisible"></span>
        </div>
      </div>
      <el-divider></el-divider>
      <div v-if="dataInfo"
           style="padding:16px;padding-top:0;padding-bottom:1px">
        <div style="height:44px;display:flex">
          <div style="width:338px;height:44px;display:flex;flex-direction:column;justify-content:space-between">
            <div style="color:#808080">Sync Frequency</div>
            <div style="color:#404040">{{dataInfo.syncRate}}</div>
          </div>
          <div style="width:338px;height:44px;display:flex;flex-direction:column;justify-content:space-between">
            <div style="color:#808080">Last successful data acquisition</div>
            <div style="color:#404040">{{timeAreaFormat(dataInfo.lastSyncDate)}}</div>
          </div>
        </div>
        <div style="height:44px;display:flex;margin-top:20px">
          <div style="width:338px;height:44px;display:flex;flex-direction:column;justify-content:space-between">
            <div style="color:#808080">API - Dataset</div>
            <div :style="{'color':'#0050B3','text-decoration':dataInfo.odsUrl?'underline': '','cursor':dataInfo.odsUrl?'pointer': ''}" @click="goToUrl(dataInfo.odsUrl)">{{dataInfo.name}}</div>
          </div>
        </div>
        <div style="height:44px;display:flex;margin-top:20px">
          <div style="height:44px;display:flex;flex-direction:column;justify-content:space-between">
            <div style="color:#808080">API URL</div>
            <div style="color:#0050B3;text-decoration:underline;">{{dataInfo.apiPath}}</div>
          </div>
        </div>
      </div>
      <div style="padding:15px">
        <el-header style="height:auto;padding:0;padding-top:1px;">
          <LogTitle />
        </el-header>
        <!-- <div class="log_function_info">
          <LogFunctionInfo :subject-code="datailInfo.sync.subjectCode"
                           :item-info="datailInfo"
                           :item-title="itemTitle" />
        </div> -->
        <div>
          <LogListInfo ref="LogListInfo"
                       :action=datailInfo.action
                       :subject-code="subjectCode" />
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
// import mixinViewModule from '@/mixins/view-module'
import moment from 'moment'
import LogTitle from './components/LogTitle'
import LogListInfo from './components/LogListInfo'

export default {
  components: {
    LogTitle, LogListInfo
  },
  // mixins: [mixinViewModule],
  props: {
    subjectCode: String,
    itemInfo: Object,
    isOff: Boolean
  },
  data () {
    return {
      dataInfo: {},
      dataForm: {
        searchDate: null,
        api: null,
        status: ''
      },
      detailVisible: false,
      datailInfo: {},
      dataDetailList: [],
      apiLists: [],
      statusLists: [
        { status: 200 },
        { status: 500 }
      ],
      dateRangeDefaultSetting: {
        format: 'yyyy-MM-dd',
        toDayStartDate: moment().format(),
        toDayEndDate: moment().format(),
        minDate: new Date('10/1/2019'),
        maxDate: new Date('1/1/2025'),
        weekStartDate: moment().subtract('days', 6).format(),
        weekEndDate: moment().subtract('days', 0).format(),
        monthStartDate: new Date(new Date(new Date().setDate(1)).toDateString()),
        monthEndDate: new Date(new Date(new Date(new Date().setMonth(new Date().getMonth() + 1)).setDate(0)).toDateString())
        // lastMonthStartDate: new Date(new Date(new Date(new Date().setMonth(new Date().getMonth() - 1)).setDate(1)).toDateString()),
        // lastMonthEndDate: new Date(new Date(new Date().setDate(0)).toDateString()),
        // lastYearStartDate: new Date((new Date().getFullYear()) - 1, 1, 1).toDateString(),
        // lastYearEndDate: new Date((new Date().getFullYear()) - 1, 11, 31).toDateString()
      },
      dataList: [],
      loading: false,
      timers: null
    }
  },
  computed: {
    tableHeight () {
      if (!this.isOff) {
        return window.innerHeight - 160 - 50
      } else {
        return window.innerHeight - 160 - 90
      }
    }
  },
  created () {
    // this.resetDataForm()
    // this.getDataList()
    this.$root.eventBus.$on('refreshList', () => {
      this.getDataList()
    })
  },
  beforeDestroy () {
    this.$root.eventBus.$off('refreshList')
    clearInterval(this.timers)
  },
  watch: {
  },
  methods: {
    getStatus (row) {
      if (!row.lastSyncDate && !row.status) {
        return 'Pending'
      }

      if (row.status === '200 OK') {
        return 'Succeeded'
      }

      return 'Failed'
    },
    goToUrl (url) {
      if (!url) return false
      this.detailVisible = false
      this.$emit('handleClose')
      this.$router.push(url)
    },
    openedHander () {
      if (this.$refs.LogListInfo) {
        this.$refs.LogListInfo.getDataList()
        this.$refs.LogListInfo.resetDataForm()
        this.getInfo()
      }
      this.$emit('closeVisible')
    },
    getInfo () {
      this.loading = true
      var _self = this
      const params = {
        // tenantId: this.$store.state.user.tenantCode,
        action: _self.datailInfo.action,
        subjectCode: _self.subjectCode
        // status: this.dataForm.status
        // interfaceName: this.dataForm.api
      }
      _self.$interface.apiManager.getInfoApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return _self.$message.error(res.msg)
        }
        _self.loading = false
        if (res.data) {
          _self.dataInfo = res.data
        }
      }).catch(() => {
        _self.loading = false
      })
    },
    closedHander () {
      if (this.$refs.LogListInfo) {
        this.$refs.LogListInfo.dataList = []
      }
      this.dataInfo = {}
    },
    refreshData () {
      if (this.$refs.LogListInfo) {
        this.$refs.LogListInfo.getDataList()
        this.$refs.LogListInfo.resetDataForm()
        this.getInfo()
      }
    },
    timeAreaFormat (time) {
      if (time) {
        return moment.tz(time, this.$store.state.user.timezoneId).format('MM/DD/YYYY HH:mm') + ' ' + moment.tz(time, this.$store.state.user.timezoneId).format('zz')
      } else {
        return time
      }
    },
    statusStyle (row) {
      if (!row.lastSyncDate && !row.status) {
        return 'status_nosucces'
      }

      if (row.status === '200 OK') {
        return 'status_succes'
      }

      return 'status_warning'
    },
    resetDataForm () {
      this.dataForm.searchDate = [this.dateRangeDefaultSetting.toDayStartDate, this.dateRangeDefaultSetting.toDayEndDate]
    },
    getDataList () {
      this.loading = true
      // var _self = this
      const params = {
        // tenantId: this.$store.state.user.tenantCode,
        subjectCode: this.subjectCode,
        status: this.dataForm.status
        // action: this.dataForm.api
      }
      if (params.status === '') {
        delete params.status
      }
      this.$interface.apiManager.getConnectorDetailInfo(params).then(({ data: res }) => {
        if (res.code !== 0) {
          this.loading = false
          return this.$message.error(res.msg)
        }
        this.loading = false
        for (var i in res.data) {
          res.data[i].btnLoading = false
        }
        this.dataList = res.data
        this.$root.eventBus.$emit('datalistBus', res.data)
      }).catch(() => { this.loading = false })
    },
    showDetail (row) {
      this.datailInfo = row
      this.detailVisible = true
    },
    manuallySync (data, index) {
      data.btnLoading = true
      this.dataList.splice(index, 1, data)
      const params = {
        tenantCode: this.$store.state.user.tenantCode,
        apiServiceName: data.apiService,
        client: data.client,
        params: {
          action: data.action
        }
      }
      this.$interface.apiManager.postManuallySyncAPI(params).then(({ data: res }) => {
        if (res.code !== 0) {
          data.btnLoading = false
          return this.$message.error(res.msg)
        }
        // this.$message.success(res.msg)
        // data.btnLoading = false
        this.syncResult(data, index)
      }).catch(() => {
        data.btnLoading = false
      })
    },
    clearnData () {
      clearInterval(this.timers)
      this.dataList = []
    },
    syncStart (data, index) {
      clearInterval(this.timers)
      this.timers = setInterval(() => {
        this.syncResult(data, index)
      }, 5000)
    },
    syncResult (data, index) {
      const params = {
        tenantCode: this.$store.state.user.tenantCode,
        action: data.action,
        client: data.client,
        lastSyncDate: data.lastSyncDate
      }
      this.$interface.apiManager.getSyncResult(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (res.data) {
          if (moment(data.lastSyncDate).isBefore(res.data.time)) {
            clearInterval(this.timers)
            const temp = {
              ...data
            }
            if (res.data.status === 'OK') {
              temp.status = '200 OK'
              temp.lastSyncDate = res.data.time
              temp.btnLoading = false
              this.dataList.splice(index, 1, temp)
            } else {
              temp.status = 'Failed'
              temp.btnLoading = false
              temp.lastSyncDate = res.data.time
              this.dataList.splice(index, 1, temp)
            }
          }
        } else {
          this.syncStart(data, index)
        }
        // data.btnLoading = false
      }).catch(() => {
        data.btnLoading = false
      })
    },
    tableRowClassName ({ row, rowIndex }) {
      if (row.btnLoading) {
        return 'loading-start'
      }
      this.$forceUpdate()
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-drawer {
  width: 100% !important;
}
.log_lisinfo {
  // width: calc(100% - 30px);
  // box-shadow: 0px -1px 0px 0px #F0F0F0;
  padding-top: 16px;
  .el-card__body {
    padding: 0 !important;
    padding-left: 0 !important;
    padding-right: 0 !important;
  }
  .query_condtions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    .condition_rg {
      margin-bottom: 5px !important;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      > span {
        width: 200px;
        margin-right: 20px;
        .e-input-group-icon {
          border: 0;
        }
      }
    }
    .condition_lf {
      .el-input__inner {
        border: 0;
      }
      .el-input__inner::-webkit-input-placeholder {
        color: #404040;
      }
      .el-input__inner:-moz-placeholder {
        color: #404040;
      }
      .el-input__inner:-ms-input-placeholder {
        color: #404040;
      }
    }
  }
  ::v-deep .log_list_headers {
    height: 48px;
    // background-color: #f5f7fa !important;
    box-shadow: 1px 1px 0px 0px #f0f0f0;
    border-radius: 2px 0px 0px 0px;
    padding: 0;
  }
  .status_succes {
    background: #f0f9eb;
    border-radius: 2px;
    font-size: 14px;
    font-weight: 400;
    color: #67c23a;
    padding: 2px 8px;
  }
  .status_nosucces {
    background: #fef0f0;
    border-radius: 2px;
    font-size: 14px;
    font-weight: 400;
    color: #f56c6c;
    padding: 2px 8px;
  }
  .status_warning {
    background: #fef0f0;
    border-radius: 2px;
    font-size: 14px;
    font-weight: 400;
    color: #e6a23c;
    padding: 2px 8px;
  }
  .log_kist_info_dialog {
    ::v-deep .el-table__body-wrapper {
      max-height: 400px;
      overflow-y: auto;
    }
  }
}
::v-deep .el-drawer {
  width: 100% !important;
}
.cuser:hover {
  cursor: pointer;
  color: #138dc7;
  background-color: #e6f7ff;
  border-radius: 4px;
}
.cusers:hover {
  cursor: pointer;
}
::v-deep .el-drawer__header {
  margin-bottom: 0 !important;
}
</style>
<style>
.loading-start{
  /* background:url('https://oss.mspbots.ai/app/gif/loading1.gif') no-repeat !important */
}
</style>
